/*
 * ClientMessage.cpp
 *
 */

#include "ClientMessage.h"
#include "http/HttpCodes.h"
#include "http/HttpParser.h"

ClientMessage::ClientMessage(Socket* socket, const ServerConfig& config, LogFile& log, const std::string& id):
socket(socket), host(config, log, id), done(false), id(id), logFile(log) {}

ClientMessage::~ClientMessage() {
	delete socket;
}

const std::string& ClientMessage::getId() const {
	return id;
}

int ClientMessage::getElapsedTime() const {
	return creationTime.getElapsedTimed();
}

bool ClientMessage::finished() const {
	return done;
}

void ClientMessage::sendErrorRespone(HttpProtocol& protocol, int code) {
	try {
		HttpResponse response;
		host.errorProcess(response, code);
		protocol.sendResponse(response);
	}
	catch (const SocketException& e) {}
}

void ClientMessage::run() {
	HttpProtocol protocol(*socket);
	try {
		const HttpRequest* request = protocol.recvRequest();
		HttpResponse response;
		host.generateResponse(response, *request);
		protocol.sendResponse(response);
		socket->close();
		done = true;
	}
	catch (const ParserException& e) {
		// Request error
		sendErrorRespone(protocol, e.errno());
		logFile.addClientError(id, std::string(e.what()));
		socket->close();
		done = true;
	}
	catch (const SocketException& e) {
		// Error de conexión
		socket->close();
		done = true;
	}
	catch (...) {
		// Error no contemplado
		logFile.addSystemError("Error inesperado en el cliente " + id);
		socket->close();
		done = true;
	}
}

void ClientMessage::die() {
	Thread::die();
	socket->shutdown();
	host.terminate();
}
